//
//  XKRechargeController.m
//  xk100
//
//  Created by xiaokang on 2017/5/27.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#define kWaiting          @"正在获取支付凭据,请稍后..."
#define kMaxAmount        @"100000"

#define kUrlScheme      @"xiaokang100" // 这个是你定义的 URL Scheme，支付宝、微信支付、银联和测试模式需要。


#import "XKRechargeController.h"
#import "XKRechargeView.h"
@interface XKRechargeController ()<GopayNewPlatformDelegate>
@property (nonatomic, strong) XKRechargeView *rechargeView;
@property (nonatomic, strong) GopayNewPlatform *gopayNewPlatform;
@end

@implementation XKRechargeController

#pragma mark - 生命周期方法
// 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _rechargeView.firstResponder = YES;
}

- (void)setupUI {
    
    _rechargeView = [XKRechargeView new];
    
    @weakify(self);
    _rechargeView.rechargeConfirmBlock = ^(UIButton *sender, NSString *channel, NSString *moneyCount) {
        if (moneyCount.doubleValue == 0.0) {
            [SVProgressHUD showInfoWithStatus:@"请输入充值金额!"];
            return;
        }
        
        if (moneyCount.doubleValue < 100) {
            [SVProgressHUD showInfoWithStatus:@"单笔充值额度不能小于100元!"];
            return;
        }
        
        if (IsEmptyStr(channel)) {
            [SVProgressHUD showInfoWithStatus:@"请选择支付方式!"];
            return;
        }
        
        @strongify(self);
        [self rechargeArgumentsWithMoney:moneyCount channel:channel];
    };
    
    [self.view addSubview:self.rechargeView];
    [self.rechargeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
}


#pragma mark - 获取账单编号并调起支付
- (void)rechargeArgumentsWithMoney:(NSString *)money channel:(NSString *)channel {
    [SVProgressHUD show];
    
    NSString *tmapStr  = [NSString getTimestamp];
    NSString *tempStr  = [NSString stringWithFormat:@"%@%@",APP_KEY_STRING,tmapStr];
    NSString *tokenStr = [tempStr md5String];
    NSNumber *time     = [NSNumber numberWithInteger:tmapStr.integerValue];
    NSNumber *uid      = [NSNumber numberWithInteger:[[UserDefaults objectWithKey:@"uid"] integerValue]];
    NSString *apptoken = [UserDefaults objectWithKey:@"apptoken"];
    
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    [dictM setObject:tokenStr   forKey:@"token"];
    [dictM setObject:time       forKey:@"time"];
    [dictM setObject:uid        forKey:@"uid"];
    [dictM setObject:apptoken   forKey:@"apptoken"];
    
    [dictM setObject:money      forKey:@"number"];
    [dictM setObject:channel    forKey:@"type"];
    
    @weakify(self);
    [APIManager POSTRequestWith:(APIPOSTRequestState_RechargeOrderNumber) parameters:@{@"number":money, @"type":channel} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        // 国付宝
        if ([channel isEqualToString:@"gpay"]) {
            [self go_pay_withOrder:successDict[@"data"][@"ordersn"]];
            
            // Ping++(微信支付和国付宝支付)
        } else {
            [Pingpp createPayment:successDict viewController:self appURLScheme:kUrlScheme withCompletion:^(NSString *result, PingppError *error) {
                NSLog(@"completion block: %@", result);
                if (error == nil) {
                    NSLog(@"PingppError is nil");
                    [SVProgressHUD showSuccessWithStatus:@"支付成功!"];
                    self.rechargeView.monetCount = @"";
                    self.rechargeView.channel = @"";
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                } else {
                    NSLog(@"PingppError: code=%lu msg=%@", (unsigned  long)error.code, [error getMsg]);
                    [SVProgressHUD showErrorWithStatus:@"支付失败!"];
                }
            }];
        }

    } failureBlock:^(NSDictionary *failureDict) {
        
    } errorBlock:^(NSError *error) {
        
    }];
    
    
    
//    [PPNetworkHelper POST:[NSString stringWithFormat:@"%@%@",base_url,Recharge_Url] parameters:dictM success:^(id successDict) {
//        [SVProgressHUD dismiss];
//        
//        
//        if (![successDict[@"flag"] isEqualToString:@"Success"]) {
//            [SVProgressHUD showErrorWithStatus:@"订单获取失败!"];
//            
//        } else {
//            
//            // 国付宝
//            if ([channel isEqualToString:@"gpay"]) {
//                [self go_pay_withOrder:successDict[@"data"][@"ordersn"]];
//                
//                // Ping++(微信支付和国付宝支付)
//            } else {
//                [Pingpp createPayment:successDict viewController:self appURLScheme:kUrlScheme withCompletion:^(NSString *result, PingppError *error) {
//                    NSLog(@"completion block: %@", result);
//                    if (error == nil) {
//                        NSLog(@"PingppError is nil");
//                        [SVProgressHUD showSuccessWithStatus:@"支付成功!"];
//                        self.rechargeView.monetCount = @"";
//                        self.rechargeView.channel = @"";
//                        
//                    } else {
//                        NSLog(@"PingppError: code=%lu msg=%@", (unsigned  long)error.code, [error getMsg]);
//                        [SVProgressHUD showErrorWithStatus:@"支付失败!"];
//                    }
//                }];
//            }
//        }
//        
//    } failure:^(NSError *error) {
//        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
//    }];
    
}

#pragma mark - 国付宝移动支付
- (void)go_pay_withOrder:(NSString *)order{
    
    NSString *tranDateTime = [NSString getCurrentTimeStringWithFormatter:@"yyyyMMddHHmmss"];
    NSMutableDictionary *sendParameters = [NSMutableDictionary dictionary];
    [sendParameters setValue:@"2.2" forKey:@"version"];
    [sendParameters setValue:@"2" forKey:@"charset"];
    [sendParameters setValue:@"1" forKey:@"language"];
    [sendParameters setValue:@"1" forKey:@"signType"];
    [sendParameters setValue:@"8888" forKey:@"tranCode"];
    [sendParameters setValue:@"0000046643" forKey:@"merchantID"];
    [sendParameters setValue:order forKey:@"merOrderNum"];
    [sendParameters setValue:_rechargeView.monetCount forKey:@"tranAmt"];
    [sendParameters setValue:@"0.00" forKey:@"feeAmt"];
    [sendParameters setValue:@"156" forKey:@"currencyType"];
    [sendParameters setValue:@"" forKey:@"frontMerUrl"];
    [sendParameters setValue:@"https://jiaoyi.xiaokang100.com/pay/gpay/notify.php" forKey:@"backgroundMerUrl"];
    [sendParameters setValue:tranDateTime forKey:@"tranDateTime"];
    [sendParameters setValue:@"0000000002000008695" forKey:@"virCardNoIn"];
    [sendParameters setValue:@"127.0.0.1" forKey:@"tranIP"];
    [sendParameters setValue:@"1" forKey:@"isRepeatSubmit"];
    [sendParameters setValue:@"" forKey:@"goodsName"];
    [sendParameters setValue:@"" forKey:@"goodsDetail"];
    
    // 2.1版本修改字段
    [sendParameters setValue:@"MAPP" forKey:@"buyerName"];
    [sendParameters setValue:@"" forKey:@"buyerContact"];
    [sendParameters setValue:@"" forKey:@"merRemark1"];
    [sendParameters setValue:@"" forKey:@"merRemark2"];
    [sendParameters setValue:[self createSignValueStringWithOrderNumber:order tranDataTime:tranDateTime] forKey:@"signValue"];
    
    // 快捷身份验证参数
    [sendParameters setValue:@"" forKey:@"buyerRealName"];
    [sendParameters setValue:@"" forKey:@"buyerRealMobile"];
    [sendParameters setValue:@"" forKey:@"buyerRealBankAcctNum"];
    [sendParameters setValue:@"" forKey:@"buyerRealCertNo"];
    
    NSLog(@"充值请求参数:%@",[NSString jsonToString:sendParameters]);
    
    self.gopayNewPlatform = [[GopayNewPlatform alloc] init];
    self.gopayNewPlatform.delegate = self;
    [self.gopayNewPlatform startGopayWithParameters:sendParameters];
}


#pragma mark ------GopayNewPlatformDelegate
-(void)gopayDidClosed {
    _rechargeView.monetCount = @"";
    _rechargeView.channel = @"";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

/*
 signValue加密域生成规则如下：
 version=[]tranCode=[]merchantID=[]merOrderNum=[]tranAmt=[]feeAmt=[]tranDateTime=[]frontMerUrl=[]backgroundMerUrl=[]orderId=[]gopayOutOrderId=[]tranIP=[]respCode=[]gopayServerTime=[]VerficationCode=[]
 version=[%@]tranCode=[%@]merchantId=[%@]merOrderNum=[%@]merAcct=[%@]tranDateTime=[%@]charset=[%@]signType=[%@]VerficationCode=[12345678]
 []内为相应域对应的值，VerficationCode为商户的身份识别码。
 
 merRemark1加密域生成规则如下：
 version=[]tranCode=[]merchantID=[]merOrderNum=[]buyerContact=[] VerficationCode=[]
 []内为相应域对应的值，VerficationCode为商户的身份识别码。
 
 */
-(NSString *)createSignValueStringWithOrderNumber:(NSString *)orderNumber tranDataTime:(NSString *)tranDataTime {
    NSString *tempString = [NSString stringWithFormat:@"version=[2.2]tranCode=[8888]merchantID=[0000046643]merOrderNum=[%@]tranAmt=[%@]feeAmt=[0.00]tranDateTime=[%@]frontMerUrl=[]backgroundMerUrl=[https://jiaoyi.xiaokang100.com/pay/gpay/notify.php]orderId=[]gopayOutOrderId=[]tranIP=[127.0.0.1]respCode=[]gopayServerTime=[]VerficationCode=[xiaokang100]",orderNumber ,_rechargeView.monetCount,tranDataTime];
    
    return [tempString md5String];
}


// 由于Ping++支付时要求必须是由两位小数,在这里对数据进行处理
- (NSString *)changeFormat:(NSString *)number {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setPositiveFormat:@"##0.00;"];
    NSNumber *num = [NSNumber numberWithDouble:number.doubleValue];
    NSString *string = [formatter stringFromNumber:num];
    return string;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
